class UsersController < ApplicationController
  before_filter :login_required
  before_filter :admin_required, :only => [ :index, :new ]
 	
 	def index
 	  @users = User.find(:all, :order => "first_name")
 	end
 	
 	def new
 	  @user = User.new
 	end
  
  def show
    @user = User.find(params[:id])
  end

	def edit
		@user = User.find(params[:id])
		
		if (@user.id != current_user.id) && (current_user.is_admin? == false)
		  flash[:notice] = "You do not have access to this page."
		  redirect_to dashboards_path
	  end
		
	end
	
	def create
		@user = User.create(params[:user])
   	
   	params[:user][:role_ids] ||= []
	  @user.roles.clear
	  params[:user][:role_ids].each do |role_id|
		  unless @user.roles.include?(Role.find(role_id))
		    @user.roles << Role.find(role_id)
	    end
	  end
   	
   	if @user.save
	    flash[:notice] = "User was successfully created."
	    redirect_to dashboards_path    
    else
      render :action => "new"
    end
  end
	
	def update	  
		@user = User.find(params[:id])
		
		params[:user][:role_ids] ||= []
	  @user.roles.clear
	  params[:user][:role_ids].each do |role_id|
		  unless @user.roles.include?(Role.find(role_id))
		    @user.roles << Role.find(role_id)
	    end
	  end
	
		if @user.update_attributes(params[:user])
		  if params[:user][:password]
		    flash[:notice] = "Password Updated"
	    else
	      flash[:notice] = "User Profile Updated"
      end
       
			redirect_to edit_user_path(@user)
		end
	end
	
	def destroy
    @user = User.find(params[:id])
    @user.destroy
  	redirect_to users_path
	end
	
end